// @Author: Duanxj
// @Description:
// @Version: 1.0.0
// @Date: 2021/4/7
// @Time: 18:29

package untils

import (
	"fmt"
	"github.com/go-gomail/gomail"
	"log"
	"math/rand"
	"strings"
	"time"
)

// 生成6位数验证码
func GenValidateCode(width int) string {
	numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numeric)
	rand.Seed(time.Now().UnixNano())
	var sb strings.Builder
	for i := 0; i < width; i++ {
		_, _ = fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
	}
	return sb.String()
}

var emailMessage *gomail.Message

//"server_host": "smtp.qq.com",
//"server_port": 25,
//"from_email": "362775721@qq.com",
//"from_passwd": "ucdpjltsazqbbjgc"
// 发送邮件方法
type EmailInfo struct {
	ServerHost string
	ServerPort int
	FromEmail  string
	FromPasswd string
}

var mailCfg = EmailInfo{
	ServerHost: "smtp.qq.com",
	ServerPort: 25,
	FromEmail:  "362775721@qq.com",
	FromPasswd: "ucdpjltsazqbbjgc",
}

func SendEmail(subject, body string, emailInfo *SendParam) {
	// var mailCfg = ReturnConfig().EmailInfo
	if len(emailInfo.Recipient) == 0 {
		fmt.Println("收件人列表为空")
		return
	}
	emailMessage = gomail.NewMessage()
	// 设置收件人
	emailMessage.SetHeader("To", emailInfo.Recipient[0])
	// 设置抄送列表
	if len(emailInfo.CC) == 0 {
		emailMessage.SetHeader("Cc", emailInfo.CC...)
	}
	// 第三个参数为发件人别名，如"dcj"，可以为空（此时则为邮箱名称）
	emailMessage.SetAddressHeader("From", mailCfg.FromEmail, "dxj")

	// 主题
	emailMessage.SetHeader("Subject", subject)

	// 正文

	emailMessage.SetBody("text/html", body)

	d := gomail.NewDialer(mailCfg.ServerHost, mailCfg.ServerPort, mailCfg.FromEmail, mailCfg.FromPasswd)

	if err := d.DialAndSend(emailMessage); err != nil {
		log.Println("邮件发送失败")
	} else {
		log.Println("已成功发送邮件到指定邮箱")
	}
}

// 定义发送邮件参数结构体
type SendParam struct {
	Recipient []string `json:"recipient"`
	CC        []string `json:"cc"`
}

// 发送验证码邮箱方法
func SendCodeEmail(recipient string, len int) string {
	var param = new(SendParam)
	code := GenValidateCode(len)
	param.Recipient = []string{recipient} //收件人邮箱地址
	SendEmail("爱家租房网的验证码", "<h1>验证码：</h1><p>"+code+"</p>", param)
	//SendEmail("surprise", "<h1>验证码：</h1><p>"+"你是一只小臭猪"+"</p>", param)
	return code
}
